$(function(){
	//下拉显示选择框
	var chooseStatus = 0;
	$('.type-option').click(function(e){
		if(chooseStatus == 1){
			$('.option-value').hide();
		}
		e.stopPropagation();
		$(this).find('.option-value').show();
		chooseStatus = 1;
	})

	//空白区域点击影藏下拉选择框
	$('body').click(function(){
		if(chooseStatus == 1){
			$('.option-value').hide();
		}
		if(titleTypeChooseStatus == 1){
			$('.option-title-value').hide();
		}
		if(selectWidth == 1){
			$('.multi_select').css({'width':'80px'});
			//$('.container').hide();
		}
	})

	//标题tab选择项
	var titleTypeChooseStatus = 0;
	$('.option-title').click(function(e){
		if(titleTypeChooseStatus == 1){
			$('.option-title-value').hide();
		}
		e.stopPropagation();
		$(this).find('.option-title-value').show();
		titleTypeChooseStatus = 1;
	})

	//国家多选样式控制
	var selectWidth = 0;
	$('.multi_select').click(function(e){
		e.stopPropagation();
		$(this).css({'width':'180px'})
		selectWidth = 1;
	})

	//下拉选择插件默认设置项
	$(".country-selct").multiselect({
		noneSelectedText: "请选择",
		checkAllText: "全选",
		uncheckAllText: '全不选',
		selectedList:1,
		minWidth: 90,
	});
	$('.ui-multiselect-menu').css({'width':'280px'});
	$('.tablelist tbody tr:odd').addClass('odd');
	//关闭
	$('.close , .cancel').click(function(){
		close();
	})



	//点击获取可选国家列表 插件扩展  解决浏览器冲突 已放置常见中
	//$('.country button span').eq(2).on('click',function(e){
	//	var i = $(this).index('.ui-multiselect','body');
	//	$('#changenum').val(i);
	//	var editsort = $('.editsort').eq(i);
	//	var campId = editsort.attr('data-camp_id');
	//	var source = editsort.attr('data-source');
	//	console.log('sort====>' + editsort +'   campid===> '+ campId +'  source===>'+source);
	//	return ;
	//	window.getCountryList(campId,source,i);
	//})

	/**
	 * 点击多选事件
	 */

	//全选
	$('.ui-multiselect-all').on('click',function(){
		var i = $(this).index('.ui-multiselect-all','body');
		var checkedValue = '';
		var checkedOption = '';
		var checklength = 0;
		$('.ui-multiselect-checkboxes').eq(i).find('.ui-corner-all').each(function(k,v){
			$(this).find('input').attr("checked",true).attr('aria-selected',true);
			checkedValue += $(this).find('input').val() + ',';
			checkedOption += $(this).find('span').html() + ',';
			checklength ++;
		})

		$('.ui-multiselect').eq(i).find('span').eq(1).html('已全选');
		$('#changeSortListValue').val(checkedValue);
		$('#changeSortListOption').val(checkedOption);
		$('.editsort').eq(i).attr('data-countryOption',checkedOption);
		$('.editsort').eq(i).attr('data-countryValue',checkedValue);
	})

	//全不选
	$('.ui-multiselect-none').on('click',function(){
		var i = $(this).index('.ui-multiselect-none','body');
		var checkedValue = '';
		var checkedOption = '';
		var checkalert = '请选择';
		$('.ui-multiselect-checkboxes').eq(i).find('.ui-corner-all').each(function(k,v){
			$(this).find('input').attr("checked",false).attr('aria-selected',false);
		})
		$('.ui-multiselect').eq(i).find('span').eq(1).html(checkalert);
		$('#changeSortListValue').val(checkedValue);
		$('#changeSortListOption').val(checkedOption);
		$('.editsort').eq(i).attr('data-countryOption',checkedOption);
		$('.editsort').eq(i).attr('data-countryValue',checkedValue);
	})


	//自定义选择
	$('.ui-corner-all').on('click',function(e){
		e.stopPropagation();
		ariaselected = $(this).find('input').attr('aria-selected');
		if(ariaselected != undefined){
			var selectedValue = '';
			var selectedOption = '';
			var selectedLength = 0;
			$(this).find('input').each(function(k,v){

				if($(this).attr('aria-selected') == 'true'){
					selectedValue += $(this).val()+',';
					selectedOption += $(this).siblings('span').html()+',';
					selectedLength ++ ;
				}
			})
			var i = $(this).find('.ui-multiselect-checkboxes').index('.ui-multiselect-checkboxes','body');
			$('.ui-multiselect').eq(i).find('span').eq(1).html(selectedLength +' selected');
			$('.editsort').eq(i).attr('data-countryOption',selectedOption);
			$('.editsort').eq(i).attr('data-countryValue',selectedValue);
			$('#changeSortListValue').val(selectedValue);
			$('#changeSortListOption').val(selectedOption);
		}
	})

	//关闭
	function close() {
		$('.tip').hide();
		$('.clover-layer').hide();
		$('.tip-container').hide();
	}

	//app关联搜索
	$('#appid-searhword').autocomplete({
		source: ''
	});

	$('#appid-searhword').keyup(function(){
		var searhWord = $(this).val();
		var url = '/?m=Admin&c=Ad&a=getSearhappId';
		url = baseUrl + 'index.php' + url;
		window.getSeachIndex(searhWord,url);
	})

	//广告管理首页 搜索
	$('#search-btn').click(function(){
		var data = window.getSearchData();
		if(data[0]=='' &&  data[1]==''){
			//alert('查询内容不能为空');
			//return false;
			var url = 'http://'+data[2] + hostUrl ;
			window.location.href = url;
			return false;
		}
		var url = 'http://'+data[2] + hostUrl + '&country='+data[0]+'&app_id='+data[1];
		window.location.href = url;
	})

	//发布预览页面搜索
	$('#search-btn-preview').on('click',function(){
		var data = window.getSearchData();
		var url = 'http://'+data[2] + hostUrl + '&country='+data[0]+'&position='+data[3];
		window.location.href = url;
	})

	//校对排序搜索
	$('#search-btn-frontlist').click(function(){
		var data = window.getSearchData();
		if(data[0] == ''){
			window.alertError('搜索国家不能为空');
			return false;
		}
		var url = 'http://'+data[2] + hostUrl + '&country='+data[0]+'&position='+data[3];
		window.location.href = url;
	})

	//文件名 获取焦点
	$('.file-name').focus(function(){
		if($('.file-name').val() == '请在此输入文件名'){
			$('.file-name').val('');
		}
	})
	//失去焦点
	$('.file-name').blur(function(){
		if($('.file-name').val() == ''){
			$('.file-name').val('请在此输入文件名');
		}
	})
	//修改排序 获取焦点
	$('.change-app-sort').focus(function(){
		var i = $(this).attr('data-index') ;
		$('.eidt-sort-btn').hide();
		$('.eidt-sort-btn').eq(i).show();
	})

	//修改排序 失去焦点
	$('.change-app-sort').blur(function(){
		$('.eidt-sort-btn').hide();
		var i = $(this).attr('data-index');
		$('#changenum').val(i);
		var sort = $(this).val();
		var data = getChangeSortCoutryList(i);
		var sortType = $('#changeSortType').attr('date-type');
		if (data[0] == '' || data[0] == '请选择') {
			window.alertError('请选择国家');
			return false;
		}else if(sort == ''){
			window.alertError('排序不能为空');
			return false;
		}else{
			$('#config-content').html('');
		}
			$('#config-content').html('选择国家：' + data[1]+'  ->修改排序为: '+sort + '排序方式:' + sortType );
			$('#changeSortListOption').val(data[1]);
			$('#changeSortListValue').val(data[0]);
			$('#changeSort').val(sort);
			//$('.clover-layerclover-layer').show();
			$('.tip').show();
	})



	//确认修改排序
	$('.sure').click(function(){
		var i = $('#changenum').val();
		var changeSortListOption = $('.editsort').eq(i).attr('data-countryOption');
		var changeSortListValue = $('.editsort').eq(i).attr('data-countryValue');
		var changeSort = $('#changeSort').val();
		var postion = $('#app-id-page-position').val();
		var is_advertisement = $('.editsort').eq(i).attr('data-is_advertisement');
		var camp_id = $('.editsort').eq(i).attr('data-camp_id');
		var source = $('.editsort').eq(i).attr('data-source');
		var app_id = $('.editsort').eq(i).attr('data-app_id');
		var sequence = $('#changeTimes').val();
		var sort_method = $('#changeSortType').val();

		if(changeSort != '' && changeSortListValue != ''){
			var url = '/?m=Admin&c=publish&a=recordUpdateSort';
			var sendData = "country=" + changeSortListValue +'&position=' + postion  +'&is_advertisement=' + is_advertisement +'&camp_id=' + camp_id +'&source=' + source +'&app_id=' + app_id +'&update_sort=' + changeSort +'&sort_method=' + sort_method +'&sequence=' + sequence ;

			ajax_post(url,sendData);
		}
	})


	function getChangeSortCoutryList(i){
		var data = new Array();
		data[0] = $('.editsort').eq(i).attr('data-countryValue');
		data[1] = $('.editsort').eq(i).attr('data-countryOption');
		data[2] = $('#app-id-page-position').val();
		return data;
	}




	//异步请求方法
	function ajax_post(url,sendData){
		urlStr = baseUrl + 'index.php' + url;
		var ajax = $.ajax({
			type: "POST",
			url: urlStr,
			data: sendData,
			timeout:15000,
			success: function(data){
				if (!data.match("^\{(.+:.+,*){1,}\}$")){
					//json判断
					window.alertError('请求出错,返回数据异常');
					return false;
				}
				data = JSON.parse(data);
				if(data.status == 10000){
					window.alertSuccess('修改成功');
					$('#changeTimes').val(Number($('#changeTimes').val()) + 1);
				}else if( data.status == 10001 ){
					window.alertError('修改失败');
				}else if(data.status == 10002){
					window.alertError('系统错误');
				}else if(data.status == 10003){
					window.alertError('参数错误');
				}else{
					window.alertError('未知错误');
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
					window.alertError('服务器异常');
				}
			},
			complete : function(XMLHttpRequest,status){
				close();
				if(status=='timeout'){
					ajax.abort();
					window.alertError('请求超时，请稍后重试');
				}
			}
		});
	}





	//查看排期
	$('.showData').click(function(){
		var data = window.getShowData($(this));
		//$('.clover-layer').show();
		$('#view-app-date').show();
		window.getDateList(data,1);
	})

	//编辑排期
	$('.editDate').click(function(){
		var data = window.getShowData($(this));
		console.log(data);
		$('#edit-view-date').show();
		//$('.clover-layer').show();
		$('#view-app-date').show();
		var i = $(this).index('.editDate','tbody');
		$('#add-edit-ad-data').attr('ad-data-index',i);
		var changeSortListValue = $('#changeSortListOption').val();
		$('#ad-data-country').html(changeSortListValue);
		window.clearEditDateInput();
		window.getDateList(data,2);
	})



	//保存
	$('#save-edit-ad-data').on('click',function(){
		var startTime =$('#edit-ad-data-startTime').val();
		var endTime = $('#edit-ad-data-endTime').val();
		var sort = $('#edit-ad-data-sort').val();
		var id = $('#edit-add-data-id').val();
		var position = $('#app-id-page-position').val();
		//var dataStr = 'startTime='+startTime+'&endTime='+endTime+'&sort='+sort+'&id='+id;
		window.saveEditAdData(startTime,endTime,sort,id,position);

	})

	//添加档期
	$('#add-edit-ad-data').on('click',function(){
		var i = $(this).attr('ad-data-index');
		var data = window.getShowData($('.editsort').eq(i));
		var startTime = $('#edit-ad-data-startTime').val();
		var endTime = $('#edit-ad-data-endTime').val();
		var sort = $('#edit-ad-data-sort').val();
		data['startTime'] = startTime;
		data['endTime'] = endTime;
		data['sort'] = sort;
		data['data'] += "&start_time="+startTime +"&end_time="+endTime+"&sort="+sort;

		window.addAdDate(data);
	})

	//编辑保存渠道
	$('#save-edit-canal-alert').on('click',function(){
		var data = window.getCanalVal();
		window.changeCanalVal(data);
	})

	//时间显示 默认美国市区
	//$('#time-zone-country').val(moment.tz(new Date(), 'America/New_York').tz('UTC').format('YYYY-MM-DD HH:mm:ss'));
	var t =new Date() ;//'2016-03-02 00:00:00';
	var utc = moment.tz(t, 'UTC');
	$('#time-zone-country').val(utc.tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss'));


	//输入国家显示对应国家对应时间
	$('#country-searhword').blur(function(){
		var country = $(this).val();
		var country_code = 'CN';
		var country_name = '';
		if(country != ''){
			var reg = new RegExp('^[a-zA-Z]{2}');
			//var result = reg.test(country);
			var result = country.match(reg);

			if(result){
				var country_code = result[0];
				var country_name = country.substr(4);
				if(country_name){
					$('#timezone-country-name').html(country_name);
				}else{
					$('#timezone-country-name').html('');
				}
			}else{
				window.alertError('国家选项值未匹配 请选择输入后的下拉匹配项');
			}
		}

		var timezone = timezone_country[country_code];
		var nowTime = new Date();
		$('#time-zone-country').val(utc.tz(timezone).format('YYYY-MM-DD HH:mm:ss'));
	})

	//搜索值 国家对应关联搜索
	$('#country-searhword').autocomplete({
		source: baseUrl + 'index.php/?m=Admin&c=AdCountry&a=getSearhCountry'
	});

//------
})


var changeSortTypeValue = 0;

function changeSortType(num){
	var changeSortTypeObj = $('#changeSortTypeValue');
	if(num == 0){
		changeSortTypeValue = 0;
		changeSortTypeObj.text('对换排序');
		$('#changeSortType').attr('date-type','对换排序');
		$('#changeSortType').val(2);
	}else{
		changeSortTypeValue = 1;
		changeSortTypeObj.text('自动排序');
		$('#changeSortType').attr('date-type','自动排序');
		$('#changeSortType').val(1);
	}
	$('.option-value').hide();
}


(function(){
	window.getCountryList = {};
	window.showData = {};
	window.saveEditAdData = {};
	window.addAdDate = {};
	window.getDateList = {};
	window.clearEditDateInput = {};
	window.getShowData = {};
	window.getCanalVal = {};
	window.changeCanalVal = {};
	window.getSearchData = {};
	window.getSeachIndex = {};

	//var baseUrl = $('#baseUrl').val();

	//获取搜索查询值
	function getSearchData(){
		var data = new Array();
		data[0] = encodeURIComponent($("#country-searhword").val());
		data[1] = encodeURIComponent($("#appid-searhword").val());
		data[2] =  window.location.host;
		data[3] = encodeURIComponent($("#app-id-page-position").val());
		return data ;
	}

	//组合获取值
	function getShowData(obj){
		var data = new Array();
		data['app_id'] = obj.attr('data-app_id');
		data['position'] = obj.attr('data-position');
		data['camp_id'] = obj.attr('data-camp_id');
		data['source'] = obj.attr('data-source');
		data['is_advertisement'] = obj.attr('data-is_advertisement');
		data['country'] = obj.attr('data-countryValue');
		data['country-default'] = obj.attr('data-country');
		data['country'] = data['country'] == ''?data['country-default']:data['country'];
		data['data'] = "app_id=" + data['app_id']+"&position=" + data['position']+"&camp_id=" + data['camp_id']+"&source=" + data['source']+"&is_advertisement=" + data['is_advertisement']+"&country=" + data['country'];
		return data;
	}

	function getChangeTimes(baseUrl) {
		var country = $('#search-coutry').val();
		var position = $('#search-app_type').val();
		var changeTimes = $('#changeTimes').val();
		//异步请求方法
		if(country == '' || country == undefined){
			return false;
		}
		if(changeTimes == undefined || changeTimes == ''){
			return false;
		}
		console.log('排序修改次数-'+changeTimes);
		var url = '/?m=Admin&c=publish&a=getUpdateSequence';
			var urlStr = baseUrl + 'index.php' + url;
			var ajax = $.ajax({
				type: "POST",
				url: urlStr,
				data:'country='+country +'&position='+position,
				timeout:15000,
				success: function(data){
					if (!data.match("^\{(.+:.+,*){1,}\}$")){
						//json判断
						window.alertError('请求出错,返回数据异常');
						return false;
					}
					data = JSON.parse(data);
					if(data.status == 10000){
						$('#changeTimes').val(data.sequence);
						//window.alertSuccess('操作成功');
					}else if( data.status == 10001 ){
						window.alertError('获取修改次数失败');
					}else if(data.status == 10002){
						window.alertError('获取修改次数系统错误');
					}else if(data.status == 10003){
						window.alertError('获取修改次数参数错误');
					}else{
						window.alertError('获取修改次数未知错误');
					}

				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
						window.alertError('服务器异常');
					}
				},
				complete : function(XMLHttpRequest,status){
					close();
					if(status=='timeout'){
						ajax.abort();
						window.alertError('请求超时，请稍后重试');
					}
				}
			});

	}

	/**
	 * 获取国家列表
	 */
	function getCountryList(campId,source,i){
		var url = '/?m=Admin&c=publish&a=getCountry';
		var urlStr = baseUrl + 'index.php' + url;
		$('.ui-multiselect-checkboxes').eq(i).html('<div class="loading" style="display: block;left: 38%;"></div>');
		var ajax = $.ajax({
			type: "POST",
			url: urlStr,
			data:'camp_id='+campId +'&source='+source,
			timeout:15000,
			success: function(data){
				if (!data.match("^\{(.+:.+,*){1,}\}$")){
					//json判断
					window.alertError('返回格式数据不正确');
					return false;
				}
				data = JSON.parse(data);
				if(data.status == 10000){
					var str = '';
					if(data.countrys.length<1){
						var defaultCountry = $('#search-coutry').val();
						str += '<li class=""><label title="" class="ui-corner-all ui-state-hover"><input name="" value="'+defaultCountry+'" type="checkbox"><span style="color: #666;">'+defaultCountry+'</span></label></li>';
					}else{
						$.each(data.countrys, function(k, v) {
							str += '<li class=""><label title="" class="ui-corner-all"><input  name="" value="'+v+'"  type="checkbox"><span>'+v+'</span></label></li>';
						})
					}

					$('.ui-multiselect-checkboxes').eq(i).html(str);
				}else if( data.status == 10001 ){
					$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数失败');
					window.alertError('获取修改次数失败');
				}else if(data.status == 10002){
					$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数系统错误');
					window.alertError('获取修改次数系统错误');
				}else if(data.status == 10003){
					$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数参数错误');
					window.alertError('获取修改次数参数错误');
				}else{
					$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数未知错误');
					window.alertError('获取修改次数未知错误');
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
					window.alertError('服务器异常');
				}
			},
			complete : function(XMLHttpRequest,status){
				close();
				if(status=='timeout'){
					ajax.abort();
					window.alertError('请求超时，请稍后重试');
				}
			}
		});
	}


	/**
	 * 编辑广告时间
	 */
	function saveEditAdData(startTime,endTime,sort,id,position){
		var url = '/?m=Admin&c=Ad&a=saveEditAdData';
		var urlStr = baseUrl + 'index.php' + url;
		var dataStr = 'startTime='+startTime+'&endTime='+endTime+'&sort='+sort+'&id='+id+'&position='+position;
		var ajax = $.ajax({
			type: "POST",
			url: urlStr,
			data:dataStr ,
			timeout:15000,
			success: function(data){
				if (!data.match("^\{(.+:.+,*){1,}\}$")){
					//json判断
					window.alertError('请求出错');
					return false;
				}
				data = JSON.parse(data);
				if(data.status == 10000){
					var str = '';
					//var str = '<tr class="edit-ad-data-'+id+'"><th>'+id+'</th><th>1027230451</th><th>AE</th><th>'+id+'</th><th>'+id+'</th><th>1</th><th><a href="javascript:editAdData(\''+ id +'\',\''+startTime+'\',\''+end_time+'\',\''+sort+'\');">编辑</a></th><th><a href="javascript:delAdData(\''+ id +'\');'>删除</a></th></tr>';
					var str ='<th>'+id+'</th><th>1027230451</th><th>AE</th><th>'+startTime+'</th><th>'+endTime+'</th><th>'+sort+'</th><th><a href="javascript:editAdData(\''+ id +'\',\''+startTime+'\',\''+endTime+'\',\''+sort+'\');">编辑</a></th><th><a href="javascript:delAdData(\''+ id +'\');">删除</a></th>'
					$('.edit-ad-data-'+id).html(str);
					window.alertSuccess('修改内容保存成功');
				}else if( data.status == 10001 ){
					//$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数失败');
					window.alertError('修改失败,请确认修改内容是否与之前内容相同');
				}else if(data.status == 10002){
					//$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数系统错误');
					window.alertError('获取修改次数系统错误');
				}else if(data.status == 10003){
					//$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数参数错误');
					window.alertError('获取修改次数参数错误');
				}else{
					//$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数未知错误');
					window.alertError('获取修改次数未知错误');
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
					window.alertError('服务器异常');
				}
			},
			complete : function(XMLHttpRequest,status){
				close();
				if(status=='timeout'){
					ajax.abort();
					window.alertError('请求超时，请稍后重试');
				}
			}
		});
	}
	//data['data'] += "&start_time="+startTime +"&end_time="+endTime+"&sort="+sort;
	function addAdDate(adData){
		console.log(adData);
		var url = '/?m=Admin&c=Publish&a=lockCpt';
		var urlStr = baseUrl + 'index.php' + url;
		var ajax = $.ajax({
			type: "POST",
			url: urlStr,
			data: adData['data'],
			timeout:15000,
			success: function(data){
				if (!data.match("^\{(.+:.+,*){1,}\}$")){
					//json判断
					window.alertError('请求出错');
					return false;
				}
				data = JSON.parse(data);
				if(data.status == 10000){

					//var str ='<tr><th>new</th><th>1027230451</th><th>AE</th><th>'+adData.startTime+'</th><th>'+adData.endTime+'</th><th>'+adData.sort+'</th><th><a href="javascript:editAdData("id",\''+adData.startTime+'\',\''+adData.endTime+'\',\''+adData.sort+'\');">编辑</a></th><th><a href="javascript:delAdData("id");">删除</a></th></tr>'
					//var str ='<tr><th></th><th>1027230451</th><th>AE</th><th>'+adData.startTime+'</th><th>'+adData.endTime+'</th><th>'+adData.sort+'</th><th></th><th></th></tr>'
					//$('.dataList').append(str);
					//添加完成
					window.alertSuccess('添加成功');
					close();
					var index = $('#add-edit-ad-data').attr('ad-data-index');
					console.log(index);
					var dataObj = $('.editDate').eq(index);
					var data = window.getShowData(dataObj);
					console.log(data);
					window.getDateList(data,2);
					$('#edit-view-date').show();
				}else if( data.status == 10001 ){
					//$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数失败');
					window.alertError(data.info);
				}else if(data.status == 10002){
					//$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数系统错误');
					window.alertError(data.info);
				}else if(data.status == 10003){
					//$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数参数错误');
					window.alertError(data.info);
				}else{
					//$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数未知错误');
					window.alertError(data.info);
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
					window.alertError('服务器异常');
				}
			},
			complete : function(XMLHttpRequest,status){
				close();
				if(status=='timeout'){
					ajax.abort();
					window.alertError('请求超时，请稍后重试');
				}
			}
		});
	}


	function getDateList(obj,num){
		var url = '/?m=Admin&c=Ad&a=getDateList';
		var urlStr = baseUrl + 'index.php' + url;
		var ajax = $.ajax({
			type: "POST",
			url: urlStr,
			data:obj['data'],
			timeout:15000,
			success: function(data){
				if (!data.match("^\{(.+:.+,*){1,}\}$")){
					//json判断
					window.alertError('请求出错,返回数据异常');
					return false;
				}
				data = JSON.parse(data);
				if(data.status == 10000){
					var str = '';
					if(num==1){
						$.each(data.data, function(k,v) {
							str += '<tr><th>'+v.id+'</th><th>'+ v.app_id+'</th><th>'+ v.country+'</th><th>'+v.start_time+'</th><th>'+v.end_time+'</th><th>'+v.sort+'</th></tr>';
						})
						$('#view-app-date').show();
					}else{
						$.each(data.data, function(k,v) {
							str += '<tr class="edit-ad-data-'+ v.id+'"><th>'+v.id+'</th><th>'+ v.app_id+'</th><th>'+ v.country+'</th><th>'+v.start_time+'</th><th>'+v.end_time+'</th><th>'+v.sort+'</th><th><a href="javascript:editAdData(\''+ v.id +'\',\''+v.start_time+'\',\''+v.end_time+'\',\''+v.sort+'\');" class="edit-date-alert">编辑</a></th><th><a href="javascript:delAdData(\''+ v.id +'\');">删除</a></th></tr>';
						})
						$('#edit-view-date').show();
					}

					$('.dataList').html(str);
					//$('.clover-layer').show();
					//window.alertSuccess('操作成功');

					//}else if( data.status == 10001 ){
					//	console.log('获取修改次数失败');
					//}else if(data.status == 10002){
					//	console.log('获取修改次数系统错误');
					//}else if(data.status == 10003){
					//	console.log('获取修改次数参数错误');
				}else{
					window.alertError('获取修改次数未知错误');
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
					window.alertError('服务器异常');
				}
			},
			complete : function(XMLHttpRequest,status){
				//close();
				if(status=='timeout'){
					ajax.abort();
					window.alertError('请求超时，请稍后重试');
				}
			}
		});
	}



	function getDateList(obj,num){
		var url = '/?m=Admin&c=Ad&a=getDateList';
		var urlStr = baseUrl + 'index.php' + url;
		var ajax = $.ajax({
			type: "POST",
			url: urlStr,
			data:obj['data'],
			timeout:15000,
			success: function(data){
				if (!data.match("^\{(.+:.+,*){1,}\}$")){
					//json判断
					window.alertError('请求出错,返回数据异常');
					return false;
				}
				data = JSON.parse(data);
				if(data.status == 10000){
					var str = '';
					if(num==1){
						$.each(data.data, function(k,v) {
							str += '<tr><th>'+v.id+'</th><th>'+ v.app_id+'</th><th>'+ v.country+'</th><th>'+v.start_time+'</th><th>'+v.end_time+'</th><th>'+v.sort+'</th></tr>';
						})
						$('#view-app-date').show();
					}else{
						$.each(data.data, function(k,v) {
							str += '<tr class="edit-ad-data-'+ v.id+'"><th>'+v.id+'</th><th>'+ v.app_id+'</th><th>'+ v.country+'</th><th>'+v.start_time+'</th><th>'+v.end_time+'</th><th>'+v.sort+'</th><th><a href="javascript:editAdData(\''+ v.id +'\',\''+v.start_time+'\',\''+v.end_time+'\',\''+v.sort+'\');">编辑</a></th><th><a href="javascript:delAdData(\''+ v.id +'\');">删除</a></th></tr>';
						})
						$('#edit-view-date').show();
					}

					$('.dataList').html(str);
					//$('.clover-layer').show();
					//window.alertSuccess('操作成功');

					//}else if( data.status == 10001 ){
					//	console.log('获取修改次数失败');
					//}else if(data.status == 10002){
					//	console.log('获取修改次数系统错误');
					//}else if(data.status == 10003){
					//	console.log('获取修改次数参数错误');
				}else{
					window.alertError('获取修改次数未知错误');
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
					window.alertError('服务器异常');
				}
			},
			complete : function(XMLHttpRequest,status){
				//close();
				if(status=='timeout'){
					ajax.abort();
					window.alertError('请求超时，请稍后重试');
				}
			}
		});
	}

	function clearEditDateInput(){
		$('#edit-ad-data-startTime').val('');
		$('#edit-ad-data-endTime').val('');
		$('#edit-ad-data-sort').val('');
	}

	//获取渠道
	function getCanal(num){
		var country = $('.editsort').eq(num).attr('data-country');
		var appid = $('.editsort').eq(num).attr('data-app_id');
		var camp_id = $('.editsort').eq(num).attr('data-camp_id');
		var source  = $('.editsort').eq(num).attr('data-source');
		var position = $('#search-app_type').val();
		var url = '/?Admin&c=publish&a=viewChannel';
		var urlStr = baseUrl + 'index.php' + url;
		var ajax = $.ajax({
			type: "POST",
			url: urlStr,
			data:'country='+country+'&app_id='+appid+'&position='+position+'&camp_id='+camp_id+'&source='+source,
			timeout:15000,
			success: function(data){
				if (!data.match("^\{(.+:.+,*){1,}\}$")){
					//json判断
					window.alertError('请求出错,返回数据异常');
					return false;
				}
				data = JSON.parse(data);
				var str = '';
				if(data.status == 10000){
					$.each(data.info, function(k,v) {
						if(v.is_select == 1){
							var checked =' checked="true"';
						}else{
							var checked = '';
						}
						str +='<tr><th>'+ v.id+'</th><th>'+ v.click_num+'</th><th>'+ v.download_num+'</th><th>'+ v.install_num+'</th><th>'+ v.active_num+'</th><th>'+ v.active_percentage+'</th><th>'+ v.click_percentage+'</th><th>'+ v.price_model+'</th><th>'+ v.price+'</th><th>'+ v.income+'</th><th><input name="chanel" value=" '+ v.source+'" data-id="'+ v.id+'" data-camp_id="'+ v.camp_id+'" data-source="'+ v.source+'"  type="radio" '+checked+'> '+ v.source+'</th></tr>';
					})
					$('#alert-edit-canal-tbody').html(str);
					$('#canal-edit-alert').show();
				}else if( data.status == 10001 ){
					str +='<tr style="color: #666;"><th>空</th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th></tr>';
					$('#alert-edit-canal-tbody').html(str);
					$('#canal-edit-alert').show();
					window.alertError('无渠道信息');
				}else if(data.status == 10002){
					console.log('获取修改次数系统错误');
				}else if(data.status == 10003){
					console.log('获取修改次数参数错误');
				}else{
					window.alertError('获取修改次数未知错误');
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
					window.alertError('服务器异常');
				}
			},
			complete : function(XMLHttpRequest,status){
				//close();
				if(status=='timeout'){
					ajax.abort();
					window.alertError('请求超时，请稍后重试');
				}
			}
		});
	}

	//获取渠道修改值
	function getCanalVal(){
		var selected = $("input[name='chanel']:checked");
		var source_copy = selected.attr('data-source');
		var camp_id_copy = selected.attr('data-camp_id');
		var id = selected.attr('data-id');
		var data = new Array();
		var camp_id = '';
		var source = '';
		data['data'] = 'id='+id+'&camp_id_copy='+camp_id_copy+'&source_copy='+source_copy;
		return data;
	}

	//修改渠道
	function changeCanalVal(objData){
		var url = '/?m=Admin&c=publish&a=changeChannel';
		var urlStr = baseUrl + 'index.php' + url;
		console.log(objData['data']);
		var ajax = $.ajax({
			type: "POST",
			url: urlStr,
			data:objData['data'],
			timeout:15000,
			success: function(data){
				if (!data.match("^\{(.+:.+,*){1,}\}$")){
					//json判断
					window.alertError('请求出错,返回数据异常');
					return false;
				}
				data = JSON.parse(data);
				if(data.status == 10000){
					window.alertSuccess('修改成功');
				}else if( data.status == 10001 ){
					window.alertError('无渠道信息');
				}else if(data.status == 10002){
					console.log('获取修改次数系统错误');
				}else if(data.status == 10003){
					console.log('获取修改次数参数错误');
				}else{
					window.alertError('获取修改次数未知错误');
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
					window.alertError('服务器异常');
				}
			},
			complete : function(XMLHttpRequest,status){
				//close();
				if(status=='timeout'){
					ajax.abort();
					window.alertError('请求超时，请稍后重试');
				}
			}
		});
	}

	//获取搜索appid和名称关联搜索索引
	function getSeachIndex(searhWord,urlStr){
		var ajax = $.ajax({
			type: "POST",
			url: urlStr,
			data: 'search='+searhWord,
			timeout:15000,
			success: function(data){
				if (!data.match("^\{(.+:.+,*){1,}\}$")){
					//json判断
					window.alertError('请求出错,返回数据异常');
					return false;
				}
				data = JSON.parse(data);
				if(data.status == 10000){
					//window.alertSuccess('获取成功');

					$('#appid-searhword').autocomplete({
						source: data.data
					});

				}else if( data.status == 10001 ){
					window.alertError('修改失败');
				}else if(data.status == 10002){
					window.alertError('系统错误');
				}else if(data.status == 10003){
					window.alertError('参数错误');
				}else{
					window.alertError('未知错误');
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
					window.alertError('服务器异常');
				}
			},
			complete : function(XMLHttpRequest,status){
				close();
				if(status=='timeout'){
					ajax.abort();
					window.alertError('请求超时，请稍后重试');
				}
			}
		});
	}

	//getChangeTimes(baseUrl); //取消默认查询修改次数
	window.getCountryList =  getCountryList;
	window.showData =  showData;
	window.saveEditAdData = saveEditAdData;
	window.addAdDate = addAdDate;
	window.getDateList = getDateList;
	window.clearEditDateInput = clearEditDateInput;
	window.getCanal = getCanal;
	window.getShowData = getShowData;
	window.getCanalVal = getCanalVal;
	window.changeCanalVal =changeCanalVal;
	window.getSearchData = getSearchData;
	window.getSeachIndex = getSeachIndex;
})();


function editAdData(id,startTime,endTime,sort){
	$('#edit-ad-data-startTime').val(startTime);
	$('#edit-ad-data-endTime').val(endTime);
	$('#edit-ad-data-sort').val(sort);
	$('#edit-add-data-id').val(id);
	var i = $('#changenum').val();
	//alert($(this).index('edit-date-alert','.edit-date-alert-tbody'));
	console.log(i);
	console.log($('.editDate').ea(i).attr('data-country'));
	$('#default-country').val($('.editDate').eq(i).attr('data-country'));
	adDataTab(1);
}


function delAdData(id){
	var url = '/?m=Admin&c=Ad&a=delAdDate';
	var urlStr = baseUrl + 'index.php' + url;
	var ajax = $.ajax({
		type: "POST",
		url: urlStr,
		data:'id='+id ,
		timeout:15000,
		success: function(data){
			if (!data.match("^\{(.+:.+,*){1,}\}$")){
				//json判断
				window.alertError('请求出错');
				return false;
			}
			data = JSON.parse(data);
			if(data.status == 10000){
				$('.edit-ad-data-'+id).remove();
				window.alertSuccess('删除成功');
			}else if( data.status == 10001 ){
				$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数失败');
				window.alertError('获取修改次数失败');
			}else if(data.status == 10002){
				$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数系统错误');
				window.alertError('获取修改次数系统错误');
			}else if(data.status == 10003){
				$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数参数错误');
				window.alertError('获取修改次数参数错误');
			}else{
				$('.ui-multiselect-checkboxes').eq(i).html('获取修改次数未知错误');
				window.alertError('获取修改次数未知错误');
			}

		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			if(textStatus == 'error' || errorThrown == 'Internal Server Error'){
				window.alertError('服务器异常');
			}
		},
		complete : function(XMLHttpRequest,status){
			close();
			if(status=='timeout'){
				ajax.abort();
				window.alertError('请求超时，请稍后重试');
			}
		}
	});

}


//添加编辑档期 tab切换
function adDataTab(num){
	$('.ad-date-edit-tab-title ul li a').removeClass('selected');
	//$(this).addClass('selected');
	//$(this).addClass('selected').parent('li').siblings('li').find('a').removeClass('selected');
	if(num == 1){
		$('.ad-date-edit-tab-title ul li a').eq(0).addClass('selected');
		$('#save-edit-ad-data').show();
		$('#add-edit-ad-data').hide();
		$("#ad-data-country").html($('#default-country').val());
	}else{
		$('#edit-ad-data-startTime').val('');
		$('#edit-ad-data-endTime').val('');
		$('#edit-ad-data-sort').val('');
		$("#ad-data-country").html($('#changeSortListOption').val());
		$('#save-edit-ad-data').hide();
		$('#add-edit-ad-data').show();
		$('.ad-date-edit-tab-title ul li a').eq(1).addClass('selected');
	}
}

//编辑渠道
function editCanal(num){
	window.getCanal(num);
	//$('#canal-edit-alert').show();
}